from fastapi import APIRouter, HTTPException
import requests
import json
from core.config import settings
from schemas import AnalyzeRequest, AnalyzeResponse

router = APIRouter(prefix="/ai", tags=["ai"])

@router.post("/analyze", response_model=AnalyzeResponse)
async def analyze(request: AnalyzeRequest):
    try:
        if settings.AI_PROVIDER == "lmstudio":
            # LM Studio 实现：使用 chat completions API
            url = f"{settings.LMSTUDIO_URL}/v1/chat/completions"
            prompt = f"分析类型: {request.analysisType}\n数据: {json.dumps(request.data, ensure_ascii=False)}"
            payload = {
                "model": settings.LMSTUDIO_MODEL,
                "messages": [
                    {"role": "system", "content": "使用中文回复"},
                    {"role": "user", "content": prompt}
                ],
                "temperature": 0.7,
                "max_tokens": -1,
                "stream": False
            }
            response = requests.post(url, json=payload)
            response.raise_for_status()
            result = response.json()
            analysis_text = result.get("choices", [{}])[0].get("message", {}).get("content", "No response from model")

        elif settings.AI_PROVIDER == "ollama":
            # 原有 Ollama 实现
            url = f"{settings.OLLAMA_URL}/api/generate"
            prompt = f"分析类型: {request.analysisType}\n数据: {json.dumps(request.data, ensure_ascii=False)}"
            payload = {
                "model": settings.OLLAMA_MODEL,
                "prompt": prompt,
                "stream": False
            }
            response = requests.post(url, json=payload)
            response.raise_for_status()
            result = response.json()
            analysis_text = result.get("response", "No response from model")

        else:
            raise ValueError("无效的 AI_PROVIDER 配置")

        return AnalyzeResponse(success=True, analysis=analysis_text)

    except requests.RequestException as e:
        raise HTTPException(status_code=500, detail=f"AI 请求失败: {str(e)}")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))